package com.tenglong.teacher.ui.homework;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.cuotibao.zhuoxiao.basics.utils.recyview.DividerSpaceItemDecoration;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.msg.attachment.AudioAttachment;
import com.netease.nimlib.sdk.msg.attachment.FileAttachment;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.HomeDetailInfo;
import com.tenglong.teacher.data.resultInfo.HomeWorkIM;
import com.tenglong.teacher.data.resultInfo.HomeworkDetailInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.HomeworkListAdapter;
import com.tenglong.teacher.ui.adapter.viewholder.HomeworkListViewHolder;
import com.tenglong.teacher.ui.answerq.P2PRecord;
import com.tenglong.teacher.ui.audio.MediaManager;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.publish.HomeworkCorrectingActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeworkDetailListActivity extends BaseActivity implements OnRefreshListener,HomeworkListViewHolder.OnViewHideListener {

    private RecyclerView recyclerView;
    private TextView mSubmit;
    private SmartRefreshLayout smartRefreshLayout;
    private String sessionId;
    private String title;
    private String accid;
    private P2PRecord record;
    private List<HomeDetailInfo> infos;
    private HomeworkListAdapter mAdapter;
    private boolean isFirst = true;
    private int mStatus;
    private Intent returnIntent = new Intent();
    private Map<Integer,Integer> hashMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homework_detail_list);
        initView();
        initRefreshView();
        setListeners();
        initData();
        setAdapter();
        requestData();
    }

    private void setAdapter() {
        infos = new ArrayList<>();
        mAdapter = new HomeworkListAdapter(infos,this);
        recyclerView.setAdapter(mAdapter);
    }

    private void initData() {
        sessionId = getIntent().getStringExtra("sessionid");
        title = getIntent().getStringExtra("title");
        accid = getIntent().getStringExtra("accid");
        record = new P2PRecord();
        setTitle(title);
    }

    private void setListeners() {
        mSubmit.setOnClickListener(this);
        smartRefreshLayout.setOnRefreshListener(this);
    }

    private void initRefreshView() {
        ClassicsHeader headerView = new ClassicsHeader(this);
        ClassicsFooter footView = new ClassicsFooter(this);
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        smartRefreshLayout.setRefreshHeader(headerView);
        smartRefreshLayout.setRefreshFooter(footView);
        smartRefreshLayout.setEnableLoadMore(false);
    }

    private void initView() {
        recyclerView = findViewById(R.id.list);
//        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//                super.getItemOffsets(outRect, view, parent, state);
//                int index = parent.getChildAdapterPosition(view);
//                HomeDetailInfo i = infos.get(index);
//                if (i.isTeacherPublishHomework && index == 0) {
//                    outRect.top = 0;
//                } else {
//                    outRect.left = DensityUtil.dp2px(15);
//                    outRect.right = DensityUtil.dp2px(15);
//                    outRect.top = DensityUtil.dp2px(15);
//                }
//                if (index == infos.size() - 1) {
//                    outRect.bottom = DensityUtil.dp2px(15);
//                }
//            }
//        });
        mSubmit = findViewById(R.id.submit);
        smartRefreshLayout = findViewById(R.id.smartRefreshLayout);
    }

    private void requestData() {
        if (isFirst) {
            isFirst = false;
            showProgressDialog("数据获取中...");
        }
        CreateRequestEntity.getWebService().getHomeworkMsgBySessionId(sessionId).enqueue(new Callback<BaseResult<HomeworkDetailInfo>>() {

            @Override
            public void onResponse(Call<BaseResult<HomeworkDetailInfo>> call, Response<BaseResult<HomeworkDetailInfo>> response) {
                smartRefreshLayout.finishRefresh(true);
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    mStatus = response.body().data.statu;
                    returnIntent.putExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, mStatus);
                    setResult(Activity.RESULT_OK, returnIntent);
                    List<HomeWorkIM> nim = response.body().data.list;
                    if (nim != null && nim.size() > 0) {
                        detailInfos.clear();
                        info = null;
                        direct = MsgDirectionEnum.Out;
                        for (HomeWorkIM homeWorkIM : nim) {
                            homeWorkIM.setP2PRecord(record);
                        }
                        for (HomeWorkIM homeWorkIM : nim) {
                            homeWorkIM.getDirect();
                        }
                        for (HomeWorkIM homeWorkIM : nim) {
                            sortMessage(homeWorkIM);
                        }
                        infos.clear();
                        if (detailInfos != null && detailInfos.size() > 0) {
                            HomeDetailInfo topItem = detailInfos.get(0);
                            topItem.isTeacherPublishHomework = topItem.direct == MsgDirectionEnum.Out;
                        }

                        infos.addAll(detailInfos);
                        getGoneList(infos);
                        mAdapter.notifyDataSetChanged();
                        mSubmit.setVisibility((mStatus == 1 || mStatus == 5) && infos.size() > 0 && !infos.get(infos.size() - 1).isTeacherPublishHomework
                                && infos.get(infos.size() - 1).direct == MsgDirectionEnum.In ? View.VISIBLE : View.GONE);
                        Log.e("参数", new Gson().toJson(infos));
                    } else {
                        ToastUtils.showCenterToast("服务器异常");
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<HomeworkDetailInfo>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
                smartRefreshLayout.finishRefresh(false);
            }
        });
    }

    private void getGoneList(List<HomeDetailInfo> detailInfos) {
        if(detailInfos!=null && detailInfos.size()<3){
            return;
        }
        hashMap=new HashMap<>();
        int sumSzie=detailInfos.size();
        for(int i=0;i<sumSzie;i++){
            if(i!=0 && i!=1 && i!=sumSzie-1){
                hashMap.put(i,i);
            }
        }
        mAdapter.setIntegerMap(hashMap);
    }

    @Override
    public void onViewHideClick(boolean isCheck) {
        if(isCheck){
            mAdapter.setIntegerMap(new HashMap<Integer, Integer>());
        }else{
            mAdapter.setIntegerMap(hashMap);
        }
        for(int i=0;i<detailInfos.size();i++){
            if(hashMap.containsKey(i)){
                mAdapter.notifyItemChanged(i);
            }
        }
    }

    private MsgDirectionEnum direct = MsgDirectionEnum.Out;
    private HomeDetailInfo info;
    private List<HomeDetailInfo> detailInfos = new ArrayList<>();
    private int position;

    public void sortMessage(IMMessage message) {
        if (direct != message.getDirect()) {
            info = new HomeDetailInfo(detailInfos.size());
            detailInfos.add(info);
            this.position = info.position;
            info.direct = message.getDirect();
        } else {
            if (info == null) {
                info = new HomeDetailInfo(detailInfos.size());
                detailInfos.add(info);
                this.position = info.position;
                info.direct = direct;
            }
        }
        direct = info.direct;
        if (message.getMsgType() == MsgTypeEnum.text) {
            String text = message.getContent();
            if (!TextUtils.isEmpty(text)) {
                if (text.contains("错题原因：") || text.contains("作业点评：") || text.contains("书写评分：") || text.contains("老师批语：")
                        || text.contains("错题原因:") || text.contains("作业点评:") || text.contains("书写评分:") || text.contains("老师批语:")) {
                    if (text.contains("错题原因：") || text.contains("错题原因:") || text.contains("&/")) {
                        info.errorContents.add(text);
                    } else {
                        info.evaluate = text;
                    }
                } else {
                    info.answer = text;
                }
            }
        } else if (message.getMsgType() == MsgTypeEnum.audio) {
            info.audioUrl = getImageUrl(message);
            MsgAttachment attachment = message.getAttachment();
            if (attachment instanceof AudioAttachment) {
                info.audioDuration = ((AudioAttachment) attachment).getDuration();
            }
        } else if (message.getMsgType() == MsgTypeEnum.image) {
            info.imageUrls.add(getImageUrl(message));
            if (position == info.position) {
                info.messages.add(message);
            }
        }
    }


    private String getImageUrl(IMMessage imMessage) {
        FileAttachment msgAttachment = (FileAttachment) imMessage.getAttachment();
        String path = msgAttachment.getPath();
        String thumbPath = msgAttachment.getThumbPath();
        String url = msgAttachment.getUrl();
        if (!TextUtils.isEmpty(path)) {
            return path;
        } else if (!TextUtils.isEmpty(url)) {
            return url;
        } else if (!TextUtils.isEmpty(thumbPath)) {
            return thumbPath;
        }  else {
            return "";
        }
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaManager.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaManager.resume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_HOMEWORK_CORRECTING_ACTIVITY:
                    int state = data.getIntExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, 0);
                    if (state != 0) {
                        returnIntent.putExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, state);
                    }
                    setResult(Activity.RESULT_OK, returnIntent);
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.submit:
                if (infos.size() == 0 || infos.get(infos.size() - 1).messages.size() == 0) return;
                Intent intent = new Intent(this, HomeworkCorrectingActivity.class);
                intent.putExtra(HomeworkCorrectingActivity.KEY_HOME_IM_PARAMS, (Serializable) infos.get(infos.size() - 1).messages);
                intent.putExtra(HomeworkCorrectingActivity.KEY_ACCOUNT_ID, accid);
                intent.putExtra(HomeworkCorrectingActivity.KEY_SESSION_ID, sessionId);
                startActivityForResult(intent, GlobalConstant.REQUEST_CODE_HOMEWORK_CORRECTING_ACTIVITY);
                break;
        }
    }
}
